package myGUI3;


import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.swing.JOptionPane;


public class iCalEvent3 {
	//These variables are for setting up date and time format 
	private GregorianCalendar gCal = new GregorianCalendar();
	private SimpleDateFormat timeFormat = new SimpleDateFormat("HHmmss");
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
	public TimeZone localeTZ = gCal.getTimeZone();
	
	//These variables are for day light saving time zones
	private String DSTname;
	private String STname;//Variable-timezone WITHOUT DST
	
	private String UTCoffset;
	private String sTime;
	
	//Data for properties that will be written to the .ics file
	private static final String VERSION = "VERSION:2.0\n";
	private static final String PRODID 	= "PRODID:-//teamflagler/ics314//HUYNGHIEM v2.0//EN\n";
	private String date_start;
	private String date_end;
	private String classification;
	private String priority;
	private String location;
	private String resources;
	private String description;
	private String comment;
	private String title;
	private String timestamp;
	private String frequency;
	//private String count;
	//private String interval;
	private String filename;
	
	
	/*String containing all of the appended property data*/
	private static String content ;
	
	
	//First the constructor set every variables to null
	public iCalEvent3(){
		DSTname = null;
		STname 	= null;
		sTime 	= null;
		date_start 	= null;
		date_end	= null;
		classification 	= null;
		priority	= null;
		location 	= null; 
		resources 	= null;
		description = null;
		title		= null;
		timestamp	= null;
		filename 	= null;
		frequency 	= null;
		
	}
	
	//This constructor is more specific with all of the fields specififed
	public iCalEvent3(String title, String dStart, String dEnd, String tStart, 
			String tEnd, String loc, String com, String res, String cl, String pri, String freq, String cou, String inter,String desc) {
		
		//Initialize the fields with the input
		setTitle(title);
		setFilename(title);
		setStartDate(dStart, tStart);
		setEndDate(dEnd, tEnd);
		setLocation(loc);
		setComment(com);
		setResource(res);
		setClass(cl);
		setPriority(pri);
		setDescription(desc);
		setFrequency(freq,cou,inter);
		//setCount(cou);
		//setInterval(inter);
		setTimestamp();
		setTimeZone();
	}
	
	//This method creates the ics file with the initialized property
	public boolean createFile()
	    { 
			
			BufferedWriter outputstream;
	        
	        /* Indicates successful .ics file creation */
	        Boolean isCreated;
	                
	        try
	        {	
	            outputstream = new BufferedWriter(new FileWriter(new File(filename)));
	            content = 
	                  "BEGIN:VCALENDAR\n" +
	                  VERSION +
	                  PRODID +
	                    
	                  /* Timezone component */
	                  "BEGIN:VTIMEZONE\n" +
	                  "TZID:" + localeTZ.getID() + "\n" +
	                  "BEGIN:DAYLIGHT\n" +
	                  "COMMENT:Info for daylight savings\n" +
	                  //"TZOFFSETFROM:" +  UTCoffset +
	                  "DTSTART:" + "19330430T020000\n" +
	                  "TZNAME:" +  DSTname +
	                  //"TZOFFSETTO:" + sTime +
	                  "RDATE:" + "19330430T020000\n" +
	                  "END:DAYLIGHT\n" +
	                  "BEGIN:STANDARD\n" +
	                  "COMMENT:Info for standard time\n" +
	                  //"TZOFFSETFROM:" + UTCoffset +
	                  "DTSTART:" + "19470608T020000\n" +
	                  "TZNAME:" + STname +
	                  //"TZOFFSETTO:" + sTime +
	                  "RDATE:" + "19470608T020000\n" +
	                  "END:STANDARD\n" +
	                  "END:VTIMEZONE\n" +
	                    
	                  /* Event component */
	                  "BEGIN:VEVENT\n" +
	                   comment  +
	                  "CREATED:" + dateFormat.format(gCal.getTime()) +
	                      "T" + timeFormat.format(gCal.getTime()) + "Z\n" +
	                  "UID:" + "<>" + "\n" + // Add UID here
	                  classification +
	                  priority +
	                  "DTSTART;TZID=" + localeTZ.getID() + ":" + date_start +
	                  "DTEND;TZID=" + localeTZ.getID() + ":" + date_end + 
	                  
	                  /* Event is marked as busy by default */
	                  /* User cannot change when creating .ics file */
	                  /* User can change from busy to free after importing */
	                  "TRANSP:OPAQUE\n" +
	                  title +
	                  location +
	                  resources +
	                  timestamp +
	                  description;
	            //Adding the recurrent aspects if user did so 
	            if (!(this.frequency.contains("NONE")))
	            {
	            	content = content + frequency;
	            }
	            
	            //The end of VEVENT as usual 
	            content = content + "END:VEVENT\n" + "END:VCALENDAR\n";
	           
	            
	            outputstream.write(content);
	            outputstream.close();//Close the written file
	           
	            
	            isCreated = true;
	        
	        }
	        catch(IOException ie)
	        {
	            JOptionPane.showMessageDialog(null, "Error creating file");
	            isCreated = false;
	        }
	        
	        return isCreated;
	    }
	
	///////////////////////////////////////////////
	//Now create the setting methods in the specific constructor above
	//////////////////////////////////////////////
	
	public void setTitle(String title) {this.title = "SUMMARY:" + title + "\n";}
	
	public String getTitle(String title) {return this.title;}
	
	public void setFilename(String title) {this.filename = title + dateFormat.format(gCal.getTime()) + "-" +
			timeFormat.format(gCal.getTime()) + ".ics";
	}
	
	private void setStartDate(String date, String time) {this.date_start = date + "T" + time + "\n";}
	
	private void setEndDate(String date, String time) {this.date_end = date + "T" + time + "\n";}
	
	private void setLocation(String location)	{this.location = "LOCATION:" + location + "\n";}
	
	private void setResource(String resource)	{this.resources = "RESOURCES:" + resource + "\n";}
	
	private void setClass(String classification) {this.classification = "CLASS:" + classification + "\n";}
	
	private void setPriority(String priority) {this.priority = "PRIORITY:" + priority + "\n";}
	
	private void setComment(String comment) {this.comment = "COMMENT:" + comment + "\n";}
	
	private void setFrequency(String frequency, String count, String interval) 
	{
		
		this.frequency = "RRULE:FREQ=" + frequency + ";COUNT=" + count + ";INTERVAL=" + interval + "\n";
		
	}

	
	
	private void setDescription(String description) 
		{
			description = description.replaceAll("\n", "\\\\n");
			this.description = "DESCRIPTION:" + description + "\n";
			
		}
	
	private void setTimestamp()
		{	
			this.timestamp = "DTSTAMP:" + dateFormat.format(gCal.getTime()) 
										+ "T" + timeFormat.format(gCal.getTime()) + "Z" + "\n";
		}
	
	private void setTimeZone()
		{	
			int DST = gCal.get(Calendar.DST_OFFSET);
			
			
			//Timezone user in based on computer's timezone
			
			DSTname = localeTZ.getDisplayName(true, TimeZone.LONG) + "\n";
			STname 	= localeTZ.getDisplayName(false, TimeZone.LONG) + "\n";
			
			int offset = localeTZ.getRawOffset();
			
			   
	        /* 
	         * Convert the UTC offset to (+/-)hhmm format for 
	         * standard and daylight savings in the current timezone
	        */
	        UTCoffset = String.format("%s%02d%02d\n", offset >= 0 ? "+" : "", 
	                offset / 3600000, (offset / 60000) % 60);
	        
	        sTime = String.format("%s%02d%02d\n", (offset + DST) >= 0 ? "+" : "", 
	                (offset + DST) / 3600000, ((offset + DST) / 60000) % 60);
	    }
		
	 public static  String getContent() 
	 {    
		 return content;     
	 }
	
			
}
